import {
    request,
    AbstractDiscoverCrawler,
    DiscoverCrawlerTest,
    DiscoverBook,
    DiscoverSource,
    FilterOption,
    FilterCategory,
    BookLink,
    PageResult,
    FilterCategoryType,
    formatString,
    getPathFromUrl,
} from "../../common/common_node.js";


class DiscoverCrawler extends AbstractDiscoverCrawler {
    options = {decoder: 'gbk'}

    async filterCategoryList(gender) {

        const $ = await (await request(this.source.portalUrl + '/paihang/allvisit_1.html', this.options)).doc();
        const rankOptions = [];
        const rankingnavArr = $('.rankingnav ul li a');
        rankingnavArr.each((i, e) => {
            rankOptions.push(new FilterOption({
                key: i.toString(),
                name: $(e).text(),
                value: $(e).attr("href").replace("1.html", "${pageNum}.html")
            }));
        });

        const categoryOptions = [];
        const navArr = $('.nav ul li a');
        navArr.each((i, e) => {
            const path = $(e).attr("href");
            if (!path.includes('/1')) {
                return;
            }

            categoryOptions.push(new FilterOption({
                key: i.toString(),
                name: $(e).text(),
                value: path.replace("/1", "/${pageNum}")
            }));
        })

        return [new FilterCategory({
            key: "type", name: "类型", type: FilterCategoryType.subCategories, subCategories: [
                new FilterCategory({key: "category", name: "分类", options: categoryOptions}),
                new FilterCategory({key: "rank", name: "排行榜", options: rankOptions})
            ]
        })];
    }

    async bookPage(pageNum, gender, filterParameterList) {

        const filterCategory = filterParameterList[0].subCategoriesValue;

        const url = formatString(this.source.portalUrl + filterCategory.optionsValue, {pageNum});
        const $ = await (await request(url, this.options)).doc();

        const bookArr = [];
        const pagestats = $('#pagestats');
        let pages = 1;
        if (pagestats.length > 0) {
            pages = Number.parseInt(pagestats?.text().split("/")[1]);
        }
        const that = this;
        if (filterCategory.key === 'rank') {
            const trArr = $('table.grid tbody tr').eq(0).nextAll();
            trArr.each((i, e) => {
                const tdArr = $(e).find('td');
                bookArr.push(new DiscoverBook({
                    name: tdArr.eq(0).text(),
                    author: tdArr.eq(2).text(),
                    type: tdArr.last().text(),
                    link: new BookLink({
                        subscriptionId: that.source.subscriptionId,
                        sourceId: that.source.id,
                        bookPath: getPathFromUrl(tdArr.eq(0).find('a').attr('href'))
                    })
                }));
            });
        }

        if (filterCategory.key === 'category') {
            $('.fl_right .tt').each((i, e) => {
                const tt = $(e);
                const bookName = tt.find('h3 a');

                let bookType;
                if (filterCategory.optionsValue.includes("/full")) {
                    bookType = "完结小说";
                } else {
                    bookType = $('.fl_left ul li.menucurr').text();
                }

                bookArr.push(new DiscoverBook({
                    name: bookName.text(),
                    author: tt.find('.pp .p1').text().replace('作者：', ''),
                    coverUrl: tt.find('.pic img').attr('src'),
                    type: bookType,
                    intro: tt.find('.pp .p2').text(),
                    link: new BookLink({
                        subscriptionId: that.source.subscriptionId,
                        sourceId: that.source.id,
                        bookPath: getPathFromUrl(bookName.attr('href'))
                    })
                }));
            })
        }

        return new PageResult({
            pageNum: pageNum,
            pages: pages,
            list: bookArr
        })
    }
}

const source = {
    "id": "cnbook/2",
    "name": "烈火中文网",
    "active": true,
    "portalUrl": "https://www.liehuozw.com",
    "description": null,
    "pageTurningMode": "pagination",
    "enableGenderFilter": false,
    "enableDiscover": true,
    "enableHotKeyword": false
};

await new DiscoverCrawlerTest(new DiscoverCrawler(DiscoverSource.createTestDiscoverSource(source))).run();

